<template>
  <div class="word-training-outer">
    <el-row justify="center" align="middle" style="height: 100vh">
      <el-col :span="32">
        <el-card class="main-card">
          <div class="word-training">
            <!-- 顶部导航栏 -->
            <div class="word-training__header">
              <div class="header-left">
                <h2 class="word-training__title">智能记忆</h2>
                <span class="unit-name">{{ currentUnit?.unitName }}</span>
              </div>
              <el-button @click="handleExit" type="primary" plain>
                <el-icon><Back /></el-icon>
                退出
              </el-button>
            </div>

            <!-- 单词卡片/听写卡片 -->
            <div class="word-training__content">
              <div class="word-card">
                <!-- 认知阶段和认知复习阶段 -->
                <template
                  v-if="
                    currentPhase === 'recognition' ||
                    currentPhase === 'recognitionReview'
                  "
                >
                  <!-- 单词和音标 -->
                  <div class="word-card__top">
                    <div class="word-card__word">
                      {{ currentWord?.spelling }}
                    </div>
                    <div class="word-card__phonetic">
                      {{ currentWord?.syllable }}
                    </div>
                    <el-button
                      class="sound-btn"
                      circle
                      @click="playWordSound"
                      :icon="Microphone"
                    />
                  </div>

                  <!-- 进度条 -->
                  <div class="word-card__progress">
                    <!-- <el-progress :percentage="100" status="success" /> -->
                    <!-- <el-progress
                      :text-inside="true"
                      :percentage="Number((0.2).toFixed(3)) * 100"
                      :stroke-width="18"
                      status="success"
                    /> -->

                    <el-progress
                      :percentage="studyProgress"
                      :format="progressFormat"
                      status="success"
                    />
                    <span class="progress-text">
                      {{
                        currentPhase === 'recognition'
                          ? `${recognitionCompletedCount}/${totalWords}`
                          : `${recognitionReviewCompletedCount}/${recognitionReviewWords.length}`
                      }}
                    </span>
                  </div>

                  <!-- 阶段信息 -->
                  <!-- <div class="word-card__phase-info">
                    <span
                      v-if="currentPhase === 'recognition'"
                      class="phase-tag"
                      >认知阶段</span
                    >
                    <span v-else class="phase-tag review">认知复习阶段</span>
                  </div> -->

                  <!-- 词性和词义（在确认认识状态和加强学习状态显示） -->
                  <div
                    v-if="
                      currentState === 'confirmation' ||
                      currentState === 'reinforcement'
                    "
                    class="word-card__meaning"
                  >
                    <div class="meaning-content">
                      <span class="part-of-speech">
                        {{ currentWord?.meaningZhCn.split('.')[0] }}.
                      </span>
                      <span class="meaning">
                        {{ currentWord?.meaningZhCn.split('.')[1] }}
                      </span>
                    </div>
                    <div
                      v-if="currentState === 'reinforcement'"
                      class="study-times"
                    >
                      剩余学习次数: {{ remainingStudyTimes }}
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="word-card__actions">
                    <!-- 状态1：认识判断 -->
                    <template v-if="currentState === 'recognition'">
                      <div class="countdown">{{ countdown }}s</div>
                      <div class="action-buttons">
                        <el-button
                          type="success"
                          size="large"
                          @click="handleRecognition(true)"
                        >
                          <el-icon><CircleCheckFilled /></el-icon>
                          认识
                        </el-button>
                        <el-button
                          type="danger"
                          size="large"
                          @click="handleRecognition(false)"
                        >
                          <el-icon><CircleCloseFilled /></el-icon>
                          不认识
                        </el-button>
                      </div>
                    </template>

                    <!-- 状态2：确认认识 -->
                    <template v-if="currentState === 'confirmation'">
                      <div class="action-buttons">
                        <el-button
                          type="success"
                          size="large"
                          @click="handleConfirmation(true)"
                        >
                          <el-icon><Check /></el-icon>
                          确认认识
                        </el-button>
                        <el-button
                          type="danger"
                          size="large"
                          @click="handleConfirmation(false)"
                        >
                          <el-icon><Close /></el-icon>
                          确认不认识
                        </el-button>
                      </div>
                    </template>

                    <!-- 状态3：加强学习 -->
                    <template v-if="currentState === 'reinforcement'">
                      <div class="action-buttons">
                        <el-button
                          type="primary"
                          size="large"
                          @click="handleReinforcement"
                          :icon="remainingStudyTimes > 0 ? '' : 'ArrowRight'"
                        >
                          {{
                            remainingStudyTimes > 0
                              ? `确认 (${remainingStudyTimes}/2)`
                              : '下一个'
                          }}
                        </el-button>
                      </div>
                    </template>
                  </div>
                </template>

                <!-- 听写阶段和听写复习阶段 -->
                <template v-else>
                  <!-- 进度条 -->
                  <div class="word-card__progress">
                    <el-progress
                      :percentage="studyProgress"
                      :format="progressFormat"
                      status="success"
                    />
                    <span class="progress-text">
                      {{
                        currentPhase === 'dictation'
                          ? `${dictationCompletedCount}/${totalWords}`
                          : `${dictationReviewCompletedCount}/${dictationReviewWords.length}`
                      }}
                    </span>
                  </div>

                  <!-- 第一行：词性、词义 -->
                  <div class="word-card__meaning" style="margin-bottom: 16px">
                    <div class="meaning-content">
                      <span class="part-of-speech">
                        {{ currentWord?.meaningZhCn.split('.')[0] }}.
                      </span>
                      <span class="meaning">
                        {{ currentWord?.meaningZhCn.split('.')[1] }}
                      </span>
                    </div>
                  </div>

                  <!-- 第二行：喇叭按钮、输入框 -->
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      gap: 16px;
                      margin-bottom: 16px;
                    "
                  >
                    <el-button
                      class="sound-btn"
                      circle
                      @click="playDictationSound"
                      :icon="Microphone"
                    />
                    <el-input
                      ref="dictationInputRef"
                      v-model="dictationInput"
                      placeholder="请输入单词拼写"
                      @keyup.enter="handleDictationEnter"
                      :status="dictationError ? 'error' : ''"
                      :disabled="dictationReadyForNext"
                      style="width: 240px"
                      autofocus
                    />
                    <el-icon
                      v-if="
                        !dictationError &&
                        dictationInput &&
                        dictationInput.trim().toLowerCase() ===
                          currentWord?.spelling.toLowerCase() &&
                        !dictationReadyForNext
                      "
                      style="color: #67c23a; margin-left: 8px"
                    >
                      <Check />
                    </el-icon>
                    <el-icon
                      v-if="dictationReadyForNext"
                      style="color: #409eff; margin-left: 8px; cursor: pointer"
                      @click="nextDictationWord"
                    >
                      <ArrowRight />
                    </el-icon>
                  </div>

                  <!-- 第三行：拼写错误时显示答案，拼写正确时显示音标 -->
                  <div
                    v-if="dictationShowSpelling"
                    style="text-align: center; margin-bottom: 16px"
                  >
                    <template v-if="dictationError">
                      <span
                        v-for="(ch, idx) in currentWord?.spelling.split('')"
                        :key="idx"
                        :style="{
                          color: dictationErrorMap[idx] ? '#f56c6c' : '#303133',
                          fontWeight: dictationErrorMap[idx]
                            ? 'bold'
                            : 'normal',
                          fontSize: '22px',
                          marginRight: '2px',
                        }"
                      >
                        {{ ch }}
                      </span>
                    </template>
                    <template v-else>
                      <span style="font-size: 22px; color: #409eff">
                        {{ currentWord?.syllable }}
                      </span>
                    </template>
                  </div>

                  <!-- 阶段信息 -->
                  <!-- <div class="word-card__phase-info">
                    <span v-if="currentPhase === 'dictation'" class="phase-tag"
                      >听写阶段</span
                    >
                    <span v-else class="phase-tag review">听写复习阶段</span>
                  </div> -->
                </template>
              </div>
            </div>

            <!-- 底部进度信息 -->
            <div class="word-training__footer">
              <div class="progress-info">
                <span>有效时长: {{ formatSeconds(effectiveSeconds) }}</span>
                <span>总时长: {{ formatSeconds(totalStudyTime) }}</span>

                <!-- 认知阶段统计 -->
                <template v-if="currentPhase === 'recognition'">
                  <span>认知完成单词数: {{ recognitionCompletedCount }}</span>
                  <span>需要认知的单词总个数: {{ totalWords }}</span>
                  <span>认识单词数: {{ knownWordsCount }}</span>
                  <span>不认识单词数: {{ unknownWordsCount }}</span>
                  <!-- 认知阶段文字显示蓝色 -->
                  <span class="recognition">认知阶段</span>
                </template>

                <!-- 认知复习阶段统计 -->
                <template v-if="currentPhase === 'recognitionReview'">
                  <span
                    >认知复习完成单词数:
                    {{ recognitionReviewCompletedCount }}</span
                  >
                  <span
                    >需要认知复习的单词总个数:
                    {{ recognitionReviewWords.length }}</span
                  >
                  <!-- 认知复习阶段文字显示浅蓝色 -->
                  <span class="recognition-review">认知复习阶段</span>
                </template>

                <!-- 听写阶段统计 -->
                <template v-if="currentPhase === 'dictation'">
                  <span>听写完成单词数: {{ dictationCompletedCount }}</span>
                  <span>需要听写的单词总个数: {{ totalWords }}</span>
                  <span>听写正确数: {{ dictationCorrectCount }}</span>
                  <span>听写错误数: {{ dictationErrorCount }}</span>
                  <!-- 听写阶段文字显示黄色 -->
                  <span class="dictation">听写阶段</span>
                </template>

                <!-- 听写复习阶段统计 -->
                <template v-if="currentPhase === 'dictationReview'">
                  <span
                    >听写复习完成单词数:
                    {{ dictationReviewCompletedCount }}</span
                  >
                  <span
                    >需要听写复习的单词总个数:
                    {{ dictationReviewWords.length }}</span
                  >
                  <!-- 听写复习阶段文字显示浅黄色 -->
                  <span class="dictation-review">听写复习阶段</span>
                </template>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import TASK_API from '@/api/dcyx/task.api'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Back,
  Microphone,
  CircleCheckFilled,
  CircleCloseFilled,
  Check,
  Close,
  ArrowRight,
} from '@element-plus/icons-vue'
import type {
  UserWordStatusUpdate,
  UserStudyRecordUpdate,
  Word,
} from '@/api/dcyx/memory.api'
import { useDcyxMemoryStore } from '@/store/modules/dcyx_memory.store'
import { useDcyxUnitStore } from '@/store/modules/dcyx_unit.store'
import DAILY_TIME_RECORDS_API from '@/api/dcyx/daily-tIme-records.api'

// 阶段类型定义
type StudyPhase =
  | 'recognition'
  | 'recognitionReview'
  | 'dictation'
  | 'dictationReview'
  | 'finished'
type StudyState = 'recognition' | 'confirmation' | 'reinforcement'

const router = useRouter()
const memoryStore = useDcyxMemoryStore()
const unitStore = useDcyxUnitStore()

// 阶段和状态管理
const currentPhase = ref<StudyPhase>('recognition')
const currentState = ref<StudyState>('recognition')

// 单词列表
const wordList = ref<Word[]>([])

// 认知阶段相关
const recognitionIndex = ref(0)
const knownWordsCount = ref(0)
const unknownWordsCount = ref(0)
const knownWordIds = ref<Set<number>>(new Set())
const unknownWordIds = ref<Set<number>>(new Set())
const recognitionReviewWordIds = ref<Set<number>>(new Set())

// 认知复习阶段相关
const recognitionReviewWords = ref<Word[]>([])
const recognitionReviewIndex = ref(0)
const recognitionReviewCompletedWordIds = ref<Set<number>>(new Set())

// 听写阶段相关
const dictationIndex = ref(0)
const dictationCorrectCount = ref(0)
const dictationErrorCount = ref(0)
const dictationInput = ref('')
const dictationError = ref(false)
const dictationErrorMap = ref<boolean[]>([])
const dictationReadyForNext = ref(false)
const dictationShowSpelling = ref(false)
const dictationFirstAttempt = ref<Set<number>>(new Set())
const dictationFailedWordIds = ref<Set<number>>(new Set())

// 听写复习阶段相关
const dictationReviewWords = ref<Word[]>([])
const dictationReviewIndex = ref(0)
const dictationReviewCorrectCountRef = ref(0)
const dictationReviewCompletedWordIds = ref<Set<number>>(new Set())
const dictationReviewOnceAttemp = ref<boolean>(true)

// 加强学习相关
const remainingStudyTimes = ref(2)
const countdown = ref(5)

// 时间相关
const effectiveSeconds = ref(0)
const totalStudyTime = ref(0)
const secondTimer = ref<number>()
const totalStudyTimer = ref<number>()
const countdownTimer = ref<number>()

// 有效时长相关
const idleTimer = ref<number>()
const isPaused = ref(false)
const idleLimit = 30 // 30秒无操作
const lastAction = ref(Date.now())
let pausedEffectiveSeconds = 0 // 暂停时的有效时长

// 监听用户操作
const activityEvents = ['mousemove', 'keydown', 'mousedown', 'touchstart']
const resetIdle = () => {
  lastAction.value = Date.now()
  if (isPaused.value) {
    isPaused.value = false
    // 恢复时从暂停时的有效时长继续递增
    effectiveSeconds.value = pausedEffectiveSeconds
    startSecondTimer()
    ElMessageBox.close()
  }
}

const handleIdle = () => {
  if (!isPaused.value) {
    isPaused.value = true
    // 暂停时保存当前有效时长
    pausedEffectiveSeconds = effectiveSeconds.value
    stopSecondTimer()
    ElMessageBox.alert('您已30秒无操作，已暂停计时', '提示', {
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
    })
  }
}

const startIdleTimer = () => {
  if (idleTimer.value) clearInterval(idleTimer.value)
  idleTimer.value = window.setInterval(() => {
    if (Date.now() - lastAction.value > idleLimit * 1000) {
      handleIdle()
    }
  }, 1000)
}

const stopIdleTimer = () => {
  if (idleTimer.value) clearInterval(idleTimer.value)
}

const addActivityListeners = () => {
  activityEvents.forEach((evt) => window.addEventListener(evt, resetIdle))
}
const removeActivityListeners = () => {
  activityEvents.forEach((evt) => window.removeEventListener(evt, resetIdle))
}

// 计算属性
const currentWord = computed(() => {
  switch (currentPhase.value) {
    case 'recognition':
      return wordList.value[recognitionIndex.value]
    case 'recognitionReview':
      return recognitionReviewWords.value[recognitionReviewIndex.value]
    case 'dictation':
      return wordList.value[dictationIndex.value]
    case 'dictationReview':
      return dictationReviewWords.value[dictationReviewIndex.value]
    default:
      return null
  }
})

const currentUnit = computed(() => unitStore.currentUnit)
const totalWords = computed(() => wordList.value.length)

// 认知阶段进度计算
const recognitionCompletedCount = computed(
  () => knownWordIds.value.size + unknownWordIds.value.size,
)

// 认知复习阶段进度计算
const recognitionReviewCompletedCount = computed(
  () => recognitionReviewCompletedWordIds.value.size,
)

// 听写阶段进度计算
const dictationCompletedCount = computed(
  () => dictationCorrectCount.value + dictationErrorCount.value,
)

// 听写复习阶段进度计算
const dictationReviewCompletedCount = computed(
  () => dictationReviewCompletedWordIds.value.size,
)

const studyProgress = computed(() => {
  switch (currentPhase.value) {
    case 'recognition':
      return Number(recognitionCompletedCount.value / totalWords.value) * 100
    case 'recognitionReview':
      return (
        Number(
          recognitionReviewCompletedCount.value /
            recognitionReviewWords.value.length,
        ) * 100
      )
    case 'dictation':
      return Number((dictationCompletedCount.value / totalWords.value) * 100)
    case 'dictationReview':
      return Number(
        (dictationReviewCompletedCount.value /
          dictationReviewWords.value.length) *
          100,
      )
    default:
      return 0
  }
})

// 进度条格式化
const progressFormat = (percentage: number) => `${percentage.toFixed(3)}%`

// 播放单词发音
const playWordSound = async () => {
  const word = currentWord.value?.spelling
  if (!word) return
  if ((window as any).wordAudio) {
    ;(window as any).wordAudio.pause()
    ;(window as any).wordAudio.currentTime = 0
  }
  const audioUrl = await memoryStore.playWordAudio(word)
  ;(window as any).wordAudio = new window.Audio(audioUrl)
  ;((window as any).wordAudio as HTMLAudioElement).play()
}

// 播放听写单词发音
const playDictationSound = async () => {
  const word = currentWord.value?.spelling
  if (!word) return
  if ((window as any).wordAudio) {
    ;(window as any).wordAudio.pause()
    ;(window as any).wordAudio.currentTime = 0
  }
  const audioUrl = await memoryStore.playWordAudio(word)
  ;(window as any).wordAudio = new window.Audio(audioUrl)
  ;((window as any).wordAudio as HTMLAudioElement).play()
}

// 处理退出：先 Gate 检查，未完成则回任务页
const handleExit = async () => {
  try {
    const gate = await TASK_API.getGateTodayStatus()
    const hasPending = !!gate?.hasPending
    localStorage.setItem('GATE_TODAY_STATUS', String(hasPending))
    localStorage.setItem('GATE_TODAY_STATUS_TS', String(Date.now()))
    if (hasPending) {
      router.replace('/gate/tasks')
      return
    }
  } catch { /* ignore */ }
  router.push('/work/word-training')
}

// 更新单词状态API
const updateWordStatus = async (wordId: number, learned: number) => {
  const statusData: UserWordStatusUpdate = {
    wordId,
    learned,
  }
  await memoryStore.updateUserWordStatus(statusData)

  const recordData: UserStudyRecordUpdate = {
    wordId,
    status: learned,
    source: 'znjy',
    sourceFrom: 'znjy',
  }
  await memoryStore.updateUserStudyRecord(recordData)
}

// 认知阶段：处理认识判断
const handleRecognition = async (isKnown: boolean) => {
  if (!currentWord.value) return

  const wordId = Number(currentWord.value.id)

  if (isKnown) {
    // 认识，进入确认环节
    currentState.value = 'confirmation'
  } else {
    // 不认识，记录到不认识的单词列表和需要复习的单词列表
    unknownWordIds.value.add(wordId)
    recognitionReviewWordIds.value.add(wordId)

    if (currentPhase.value === 'recognition') {
      unknownWordsCount.value++
      await updateWordStatus(wordId, 0)
    }

    // 进入加强学习
    currentState.value = 'reinforcement'
    remainingStudyTimes.value = 2
  }
  countdown.value = 5
}

// 认知阶段：处理确认认识
const handleConfirmation = async (isConfirmed: boolean) => {
  if (!currentWord.value) return

  const wordId = Number(currentWord.value.id)

  if (isConfirmed) {
    // 确认认识
    knownWordIds.value.add(wordId)
    if (currentPhase.value === 'recognition') {
      knownWordsCount.value++
      await updateWordStatus(wordId, 1)
      nextRecognitionWord()
    } else if (currentPhase.value === 'recognitionReview') {
      recognitionReviewCompletedWordIds.value.add(wordId)
      nextRecognitionReviewWord()
    }
  } else {
    // 确认不认识
    unknownWordIds.value.add(wordId)
    recognitionReviewWordIds.value.add(wordId)

    if (currentPhase.value === 'recognition') {
      unknownWordsCount.value++
      await updateWordStatus(wordId, 0)
    }

    // 进入加强学习
    currentState.value = 'reinforcement'
    remainingStudyTimes.value = 2
  }
}

// 加强学习处理
const handleReinforcement = () => {
  if (remainingStudyTimes.value > 0) {
    remainingStudyTimes.value--
    playWordSound()
  } else {
    // 加强学习完成，进入下一个单词
    if (currentPhase.value === 'recognition') {
      nextRecognitionWord()
    } else if (currentPhase.value === 'recognitionReview') {
      nextRecognitionReviewWord()
    }
  }
}

// 认知阶段：下一个单词
const nextRecognitionWord = () => {
  if (recognitionIndex.value < totalWords.value - 1) {
    recognitionIndex.value++
    currentState.value = 'recognition'
    countdown.value = 5
    startCountdown()
    playWordSound()
  } else {
    // 认知阶段完成，进入认知复习阶段
    enterRecognitionReviewPhase()
  }
}

// 进入认知复习阶段
const enterRecognitionReviewPhase = () => {
  if (recognitionReviewWordIds.value.size > 0) {
    currentPhase.value = 'recognitionReview'
    recognitionReviewWords.value = wordList.value.filter((word) =>
      recognitionReviewWordIds.value.has(Number(word.id)),
    )
    recognitionReviewIndex.value = 0
    currentState.value = 'recognition'
    countdown.value = 5
    startCountdown()
    playWordSound()
  } else {
    // 没有需要复习的单词，直接进入听写阶段
    enterDictationPhase()
  }
}

// 认知复习阶段：下一个单词
const nextRecognitionReviewWord = () => {
  // 判断如果完成认知复习的单词id集合个数等于需要认知复习的单词id集合个数，则进入听写阶段
  if (
    recognitionReviewCompletedWordIds.value.size ===
    recognitionReviewWordIds.value.size
  ) {
    // 认知复习完成，进入听写阶段
    enterDictationPhase()
    return
  }

  // 筛选出在需要认知复习的单词id集合的，但是不在完成认知复习的单词id集合的单词id
  const remainingWordIds = new Set<number>()
  recognitionReviewWordIds.value.forEach((wordId) => {
    if (!recognitionReviewCompletedWordIds.value.has(wordId)) {
      remainingWordIds.add(wordId)
    }
  })

  // 随机选出一个单词id
  const remainingWordIdsArray = Array.from(remainingWordIds)
  const randomIndex = Math.floor(Math.random() * remainingWordIdsArray.length)
  const selectedWordId = remainingWordIdsArray[randomIndex]

  // 从需要认知复习的单词列表中选出该单词，作为下一个需要认知复习的单词
  const selectedWordIndex = recognitionReviewWords.value.findIndex(
    (word) => Number(word.id) === selectedWordId,
  )

  if (selectedWordIndex !== -1) {
    recognitionReviewIndex.value = selectedWordIndex
    currentState.value = 'recognition'
    countdown.value = 5
    startCountdown()
    playWordSound()
  } else {
    // 如果找不到对应的单词，进入听写阶段
    enterDictationPhase()
  }
}

// 进入听写阶段
const enterDictationPhase = () => {
  currentPhase.value = 'dictation'
  dictationIndex.value = 0
  dictationCorrectCount.value = 0
  dictationErrorCount.value = 0
  dictationInput.value = ''
  dictationError.value = false
  dictationErrorMap.value = []
  dictationShowSpelling.value = false
  dictationReadyForNext.value = false
  dictationFirstAttempt.value.clear()
  dictationFailedWordIds.value.clear()

  playDictationSound()
  focusDictationInput()
}

// 听写阶段：输入框自动聚焦
const dictationInputRef = ref<HTMLInputElement | null>(null)
const focusDictationInput = () => {
  nextTick(() => {
    dictationInputRef.value?.focus()
  })
}

// 监听输入变化
watch(dictationInput, (val) => {
  if (val) {
    dictationShowSpelling.value = false
  }
})

// 听写阶段：处理输入
const handleDictationEnter = async () => {
  if (dictationReadyForNext.value) {
    nextDictationWord()
    return
  }

  if (!dictationInput.value || !currentWord.value) return

  const wordId = Number(currentWord.value.id)
  const isCorrect =
    dictationInput.value.trim().toLowerCase() ===
    currentWord.value.spelling.toLowerCase()
  const isFirstAttempt = !dictationFirstAttempt.value.has(wordId)
  const isOnceAttemp = dictationReviewOnceAttemp.value

  if (isCorrect) {
    // 拼写正确
    dictationError.value = false
    dictationShowSpelling.value = true
    dictationReadyForNext.value = true

    if (isFirstAttempt) {
      // 首次拼写正确
      if (currentPhase.value === 'dictation') {
        dictationCorrectCount.value++
        await updateWordStatus(wordId, 1)
      }
    }

    if (isOnceAttemp) {
      if (currentPhase.value === 'dictationReview') {
        // 在听写复习阶段，我们需要手动跟踪正确的数量
        // 这里我们使用一个单独的计数器
        dictationReviewCorrectCountRef.value++
        dictationReviewCompletedWordIds.value.add(wordId)
      }
    } else {
      if (currentPhase.value === 'dictationReview') {
        // 在听写复习阶段，没有一次成功，重置标志量；
        dictationReviewOnceAttemp.value = true
      }
    }
  } else {
    // 拼写错误
    dictationError.value = true
    dictationShowSpelling.value = true
    dictationFirstAttempt.value.add(wordId)
    // 听写复习-如果拼写错误，则需要重新拼写
    dictationReviewOnceAttemp.value = false

    if (isFirstAttempt) {
      // 首次拼写错误
      if (currentPhase.value === 'dictation') {
        dictationErrorCount.value++
        dictationFailedWordIds.value.add(wordId)
        await updateWordStatus(wordId, 0)
      }
    }

    // 生成错误高亮map
    const inputArr = dictationInput.value.trim().split('')
    const answerArr = currentWord.value.spelling.split('')
    const errorArr: boolean[] = []
    for (let i = 0; i < answerArr.length; i++) {
      errorArr.push(inputArr[i]?.toLowerCase() !== answerArr[i].toLowerCase())
    }
    dictationErrorMap.value = errorArr
  }

  playDictationSound()
}

// 听写阶段：下一个单词
const nextDictationWord = () => {
  if (currentPhase.value === 'dictation') {
    if (dictationIndex.value < totalWords.value - 1) {
      dictationIndex.value++
      dictationInput.value = ''
      dictationError.value = false
      dictationErrorMap.value = []
      dictationShowSpelling.value = false
      dictationReadyForNext.value = false
      playDictationSound()
      focusDictationInput()
    } else {
      // 听写阶段完成，检查是否需要听写复习
      if (dictationFailedWordIds.value.size > 0) {
        enterDictationReviewPhase()
      } else {
        finishStudy()
      }
    }
  } else if (currentPhase.value === 'dictationReview') {
    // 判断如果完成听写复习的单词id集合个数等于需要听写复习的单词id集合个数，则进入结束阶段
    if (
      dictationReviewCompletedWordIds.value.size ===
      dictationFailedWordIds.value.size
    ) {
      // 听写复习完成
      finishStudy()
      return
    }

    // 筛选出在需要听写复习的单词id集合的，但是不在完成听写复习的单词id集合的单词id
    const remainingWordIds = new Set<number>()
    dictationFailedWordIds.value.forEach((wordId) => {
      // 检查这个单词是否还没有被正确拼写过
      if (!dictationReviewCompletedWordIds.value.has(wordId)) {
        remainingWordIds.add(wordId)
      }
    })

    // 随机选出一个单词id
    const remainingWordIdsArray = Array.from(remainingWordIds)
    const randomIndex = Math.floor(Math.random() * remainingWordIdsArray.length)
    const selectedWordId = remainingWordIdsArray[randomIndex]

    // 从需要听写复习的单词列表中选出该单词，作为下一个需要听写复习的单词
    const selectedWordIndex = dictationReviewWords.value.findIndex(
      (word) => Number(word.id) === selectedWordId,
    )

    if (selectedWordIndex !== -1) {
      dictationReviewIndex.value = selectedWordIndex
      dictationInput.value = ''
      dictationError.value = false
      dictationErrorMap.value = []
      dictationShowSpelling.value = false
      dictationReadyForNext.value = false
      playDictationSound()
      focusDictationInput()
    } else {
      // 如果找不到对应的单词，完成学习
      finishStudy()
    }
  }
}

// 进入听写复习阶段
const enterDictationReviewPhase = () => {
  currentPhase.value = 'dictationReview'
  dictationReviewWords.value = wordList.value.filter((word) =>
    dictationFailedWordIds.value.has(Number(word.id)),
  )
  dictationReviewIndex.value = 0
  dictationReviewCorrectCountRef.value = 0 // Reset correct count for review phase
  dictationReviewCompletedWordIds.value.clear() // Reset completed word ids
  dictationInput.value = ''
  dictationError.value = false
  dictationErrorMap.value = []
  dictationShowSpelling.value = false
  dictationReadyForNext.value = false

  playDictationSound()
  focusDictationInput()
}

// 倒计时处理
const startCountdown = () => {
  if (countdownTimer.value) clearInterval(countdownTimer.value)
  countdownTimer.value = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else if (currentState.value === 'recognition') {
      // 倒计时结束，默认不认识
      handleRecognition(false)
    }
  }, 1000)
}

// 快捷键处理
const handleKeydown = (e: KeyboardEvent) => {
  if (
    currentPhase.value === 'dictation' ||
    currentPhase.value === 'dictationReview'
  ) {
    if (e.key === 'Enter') {
      handleDictationEnter()
    }
    return
  }

  // 如果是空格，再次播放音频
  if (e.key === ' ') {
    playWordSound()
  }

  if (e.key === 'ArrowRight') {
    if (currentState.value === 'recognition') {
      handleRecognition(true)
    } else if (currentState.value === 'confirmation') {
      handleConfirmation(true)
    } else if (currentState.value === 'reinforcement') {
      handleReinforcement()
    }
  } else if (e.key === 'ArrowLeft') {
    if (currentState.value === 'recognition') {
      handleRecognition(false)
    } else if (currentState.value === 'confirmation') {
      handleConfirmation(false)
    }
  }
}

// 时间相关函数
const formatSeconds = (s: number) => {
  const h = Math.floor(s / 3600)
  const m = Math.floor((s % 3600) / 60)
  const sec = s % 60
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
}

const startSecondTimer = () => {
  if (secondTimer.value) clearInterval(secondTimer.value)
  secondTimer.value = window.setInterval(() => {
    if (!isPaused.value) {
      effectiveSeconds.value++
      // 每60秒上报一次有效时长
      if (effectiveSeconds.value % 60 === 0) {
        reportEffectiveSeconds()
      }
    }
  }, 1000)
}

const stopSecondTimer = () => {
  if (secondTimer.value) clearInterval(secondTimer.value)
}

// 上报有效时长API
const reportEffectiveSeconds = async () => {
  try {
    await DAILY_TIME_RECORDS_API.addOnlineOrEffectiveSeconds({
      effectiveSeconds: 60,
      onlineSeconds: 0,
    })
    // 上报后查一次最新有效时长
    const res = await DAILY_TIME_RECORDS_API.getTodayOnlineSeconds()
    if (res?.effectiveSeconds != null) {
      effectiveSeconds.value = res.effectiveSeconds
    }
  } catch {
    /* ignore */
  }
}

const startTotalStudyTimer = () => {
  if (totalStudyTimer.value) clearInterval(totalStudyTimer.value)
  totalStudyTimer.value = window.setInterval(() => {
    totalStudyTime.value++
  }, 1000)
}

const stopTotalStudyTimer = () => {
  if (totalStudyTimer.value) clearInterval(totalStudyTimer.value)
}

// 完成学习
const finishStudy = async () => {
  currentPhase.value = 'finished'

  if (currentUnit.value) {
    const memoryScore = Math.round(
      (knownWordsCount.value / totalWords.value) * 100,
    )
    await memoryStore.saveUnitStudyStatus({
      source: 0,
      memoryCompleted: 1,
      unitId: currentUnit.value.unitId,
      memoryScore: memoryScore,
      memoryTimeConsuming: totalStudyTime.value,
    })
    await memoryStore.saveUnitStudyStats({
      unitId: currentUnit.value.unitId,
      unitTotal: totalWords.value,
      studyNumZnjy: knownWordsCount.value,
      restudyNumZnjy: unknownWordsCount.value,
      testTimeZnjy: totalStudyTime.value,
      isEndZnjy: 1,
    })
  }

  ElMessage.success(
    `学习完成！认识单词: ${knownWordsCount.value}，不认识单词: ${unknownWordsCount.value}，有效时间: ${formatSeconds(effectiveSeconds.value)}`,
  )

  // 学习完成后的轻量引导：刷新任务并根据 Gate 状态返回
  try {
    const lastId = Number(localStorage.getItem('LAST_TASK_ITEM_ID') || '0')
    if (lastId > 0) {
      await TASK_API.refreshItem(lastId)
    }
  } catch { /* ignore */ }
  try {
    const gate = await TASK_API.getGateTodayStatus()
    const hasPending = !!gate?.hasPending
    localStorage.setItem('GATE_TODAY_STATUS', String(hasPending))
    localStorage.setItem('GATE_TODAY_STATUS_TS', String(Date.now()))
    if (hasPending) {
      router.replace('/gate/tasks')
      return
    }
  } catch { /* ignore */ }
  handleExit()
}

// 页面加载
onMounted(async () => {
  const unit = await unitStore.getCurrentUnit()
  if (unit?.unitId) {
    await memoryStore.fetchWords(unit.unitId)
    wordList.value = memoryStore.wordList
  }

  startCountdown()
  playWordSound()
  window.addEventListener('keydown', handleKeydown)
  startSecondTimer()
  startTotalStudyTimer()
  startIdleTimer() // 启动空闲计时器
  addActivityListeners() // 添加活动监听器

  // 仅首次进入时获取今日有效时长
  try {
    const res = await DAILY_TIME_RECORDS_API.getTodayOnlineSeconds()
    if (res?.effectiveSeconds != null) {
      effectiveSeconds.value = res.effectiveSeconds
    }
  } catch {
    /* ignore */
  }
})

onUnmounted(() => {
  if (countdownTimer.value) clearInterval(countdownTimer.value)
  if (secondTimer.value) clearInterval(secondTimer.value)
  if (totalStudyTimer.value) clearInterval(totalStudyTimer.value)
  if (idleTimer.value) clearInterval(idleTimer.value)
  window.removeEventListener('keydown', handleKeydown)
  removeActivityListeners() // 移除活动监听器
  stopIdleTimer() // 停止空闲计时器
  stopSecondTimer() // 停止有效时间计时器
  stopTotalStudyTimer() // 停止总时间计时器
})
</script>

<style lang="scss" scoped>
.word-training-outer {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-bg-color-page);
}

.main-card {
  width: 66vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
}

.word-training {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
}

.word-training__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .unit-name {
    font-size: 16px;
    color: var(--el-text-color-secondary);
  }
}

.word-training__title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.word-training__content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.word-training__footer {
  margin-top: 24px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .progress-info {
    display: flex;
    justify-content: space-around;
    font-size: 14px;
    color: var(--el-text-color-regular);

    .recognition {
      color: #409eff; // 认知阶段 - 蓝色
    }

    .recognition-review {
      color: #a3d1ff; // 认知复习阶段 - 浅蓝色
    }

    .dictation {
      color: #e6a23c; // 听写阶段 - 黄色
    }

    .dictation-review {
      color: #f0c78a; // 听写复习阶段 - 浅黄色
    }
  }
}

.word-card {
  width: 100%;
  max-width: 600px;
  padding: 32px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  &__top {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    margin-bottom: 24px;
  }

  &__word {
    font-size: 36px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  &__phonetic {
    font-size: 20px;
    color: var(--el-text-color-secondary);
  }

  &__progress {
    // display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;

    .el-progress--line {
      margin-bottom: 15px;
      max-width: 600px;
    }

    .progress-text {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }

  &__phase-info {
    text-align: center;
    margin-bottom: 24px;

    .phase-tag {
      display: inline-block;
      padding: 4px 12px;
      background-color: var(--el-color-primary);
      color: white;
      border-radius: 16px;
      font-size: 14px;

      &.review {
        background-color: var(--el-color-warning);
      }
    }
  }

  &__meaning {
    text-align: center;
    margin-bottom: 24px;

    .meaning-content {
      font-size: 24px;
      margin-bottom: 8px;
    }

    .part-of-speech {
      color: var(--el-text-color-secondary);
      margin-right: 8px;
    }

    .study-times {
      font-size: 16px;
      color: var(--el-color-primary);
      margin-top: 8px;
    }
  }

  &__actions {
    .countdown {
      text-align: center;
      font-size: 24px;
      color: var(--el-color-primary);
      margin-bottom: 16px;
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 16px;

      .el-button {
        min-width: 120px;
      }
    }
  }
}

.sound-btn {
  font-size: 20px;
}
</style>
